﻿using System.Windows.Forms;
using Fingu.ATF.InstrumentLib;
using Fingu.ATF.Testing;
using System;
using System.Collections;
using System.Threading;
using System.Drawing;
using clsLib_ActiveDevice;
using Fingu.GFProtocol;
using Fingu.AISG;
//using Fingu.AISG;


namespace Fingu.ATF.Testing
{
    //static class Program
    //{
    //    /// <summary>
    //    /// 应用程序的主入口点。
    //    /// </summary>
    //    [STAThread]
    //    static void Main()
    //    {
    //        Application.EnableVisualStyles();
    //        Application.SetCompatibleTextRenderingDefault(false);
    //        Application.Run(new PowerEfficient());
    //    }
    //}

    ////读取测试配置文件的内容
    //public struct TestParamPowerEffective
    //{

    //}

    //public class TestingConfig : TestingConfigBase
    //{
    //    // TODO 在实际使用中应扩充此类
    //    // 应包含实际的测试功能中所用到的配置参数，如：校准参数、测试参数及指标等
    //    public string ProcessName { get; set; }
    //    public string ProductCode { get; set; }
    //    public TestParamPowerEffective[] TestParams;
    //}

    public class TestingEnter : TestingBase
    {
        #region defind variable
        
        //读取测试配置文件的内容
        public struct TestParamPowerEffective
        {
            /// <summary>
            /// date:2012-11-07
            /// author:xj
            /// content:Add a few fields, used to multiport fixture test. 
            /// </summary>
            public string PortName;
            public string ProductCommand;
            public string TestIndex;
            public string FixtureCommand;
            public string TestLimit;
        }
        
        //读取测试配置文件标签的内容
        public class TestingConfig : TestingConfigBase
        {
            // TODO 在实际使用中应扩充此类
            // 应包含实际的测试功能中所用到的配置参数，如：校准参数、测试参数及指标等
            //public string ProcessName { get; set; }
            //public string ProductCode { get; set; }
            public string TestType { get; set; }
            public TestParamPowerEffective[] TestParams;
        }

        private string CorrespondingNumberSwitch = "";

        private TestData tData;

        #endregion

        #region  instance objects

        private PowerEfficient powerEfficient = null;
        public ISignalGenerator iSG1;
        public ISpectrumAnalyzer iSA;
        public IDcPower iPM1;
        public IDcPower iPM2;        
        public TMR045 _tmr045;
        public TMR045.ICom _icom;
        /// <summary>
        /// date:2012-11-07
        /// author:xj
        /// content:
        /// defind a instance of mulitport fixture test.
        /// defind a instance of RS232.
        /// </summary>
        private GFProtocol.ILayer7 igfp;
        private ICom iCom;

        #endregion

        #region methods

        //构造函数
        public TestingEnter()
        { }
        //构造函数 - 带参数的
        public TestingEnter(HostInterface host)
        {
            Version = "S1.0";
            Author = "谢军";
            Name = "功放效率测试程序";
            iHost = host;
            CorrespondingNumberSwitch = iHost.GetCorrespondingNumber();
            powerEfficient = new PowerEfficient();
            powerEfficient.testingEnter = this;
            powerEfficient.Text = Name;
            powerEfficient.MdiParent = iHost.GetMainForm();
            powerEfficient.WindowState = FormWindowState.Maximized;
            GetConfig(typeof(TestingConfig));
            
            _tmr045 = new TMR045();
            _icom = new TMR045.ICom();

        }

        public string GetSave()
        {
            return iHost.GetSave();
        }
        //显示测试面板
        public override void ShowForm()
        {
            powerEfficient.Show();

            #region Add/2011-07-26/根据save标签的内容，确定是否使用保存按钮

            switch (getSaveType())
            {
                case "OFF":
                    powerEfficient.btSave.Visible = false;
                    break;

                case "ON":
                    powerEfficient.btSave.Visible = true;
                    break;
            }

            #endregion
        }
        //得到保存按钮是否显示的标示
        public string getSaveType()
        {
            return iHost.GetSave();
        }
        //隐藏测试面板
        public override void HideForm()
        {
            powerEfficient.Hide();
        }
        //仪表校准
        protected override void Calibrate(){ }
        //重新仪表校准
        public override void ReCalibrate() { }
        //给信号源，频谱仪指定名称
        public override bool SetInstruments(ArrayList Instruments)
        {
            bool _state = false;

            foreach (object Instrument in Instruments)
            {
                if (Instrument is ISignalGenerator)
                {
                    iSG1 = (ISignalGenerator)Instrument;
                    Instruments.Remove(Instrument);
                    break;
                }
            }

            foreach (object Instrument in Instruments)
            {
                if (Instrument is ISpectrumAnalyzer)
                {
                    iSA = (ISpectrumAnalyzer)Instrument;
                    Instruments.Remove(Instrument);
                    break;
                }
            }

            foreach (object Instrument in Instruments)
            {
                if (Instrument is IDcPower)
                {
                    iPM1 = (IDcPower)Instrument;
                    Instruments.Remove(Instrument);
                    break;
                }
            }

            foreach (object Instrument in Instruments)
            {
                if (Instrument is IDcPower)
                {
                    iPM2 = (IDcPower)Instrument;
                    Instruments.Remove(Instrument);
                    break;
                }
            }

            switch(GetTestType())
            {
                case "SinglePort-Testing":

                    if((iSG1 != null) && (iSA != null) && (iPM1 != null) && (iPM2 != null))
                    {
                        _state = true;
                    }
                    else
                    {
                        _state = false;
                    }

                    break;

                case "MulitPort-Testing":
                    //iCom is open.
                    /// <summary>
                    /// date:2012-11-07
                    /// author:xj
                    /// content:
                    /// instantiates an object of mulitport fixture test.
                    /// instantiates an object of RS232.
                    /// </summary>
                    foreach (object Instrument in Instruments)
                    {
                        if (Instrument is ICom)
                        {
                            iCom = (ICom)Instrument;
                            Instruments.Remove(Instrument);
                            break;
                        }
                    }

                    igfp = GFProtocol.Factory.MakeGFProtocol(iCom, powerEfficient);

                    iCom.Close();

                    if ((iSG1 != null) && (iSA != null) && (iPM1 != null) && (iPM2 != null) && (iCom != null))
                    {
                        _state = true;
                    }
                    else
                    {
                        _state = false;
                    }
                    break;
            }

            return _state;
        }
        //测试
        protected override void Test() { }
        //保存数据
        public void Save()
        {
            string msg, CorrespondingNb;

            CorrespondingNb = "";

            //将测试数据绘制成xml格式数据表
            GetTestDataXML();

            if (!iHost.SaveData(this._TestResult, "",
                                tData.GetXml(),
                                out msg,
                                CorrespondingNb,
                                this._CheckOutState))
            {
                throw new Exception("保存测试数据出错：" + msg);
            }
        }

        #endregion

        //将测试数据绘制成xml格式数据表
        public void GetTestDataXML()
        {
            tData = new TestData();
            tData.Content = "功放效率测试_";
            tData.Ver = "1";
            tData.Description = "这是功放效率测试数据_";

            FieldName[] fns = { new FieldName("TestRoad", "测试通路_"), 
                                new FieldName("TestResult", "E_测试结果_") };

            tData.SetFieldName(fns);

            for (int i = 0; i < this._CobTestRoad.Items.Count; i++ )
            {
                string[] datas1 = { this._CobTestRoad.Items[i].ToString(), this._TestDatas[i] };
                tData.SetData(datas1);
            }
        }

        private ComboBox _CobTestRoad;
        public void SetCobTestRoad(ComboBox cob)
        {
            this._CobTestRoad = cob;
        }
        public ComboBox GetCobTestRoad()
        {
            return this._CobTestRoad;
        }

        private string[] _TestDatas;
        public void SetTestDatas(string[] datas)
        {
            this._TestDatas = datas;
        }
        public string[] GetTestDatas() 
        {
            return this._TestDatas;
        }

        private int _TestResult;
        public void SetTestResult(int testResult)
        {
            this._TestResult = testResult;
        }
        public int GetTestResult()
        {
            return this._TestResult;
        }

        private string _CheckOutState;
        public void SetCheckOutState(string checkOutState)
        {
            this._CheckOutState = checkOutState;
        }
        public string GetCheckOutState()
        {
            return this._CheckOutState;
        }

        //////////////////////////////////////////////////////////////////////////
        /// <summary>
        /// date:2012-11-07
        /// author:xj
        /// content:
        /// get test step
        /// get product command
        /// get test index
        /// get mutliport testfixture command
        /// get test limit
        /// get test type
        /// </summary>
        public string[] GetTestStep()
        {            
            try
            {
                string[] _result = new string[((TestingConfig)testingConfig).TestParams.Length];

                for (int i = 0; i <= _result.Length - 1; i++)
                {
                    _result[i] = ((TestingConfig)testingConfig).TestParams[i].PortName.ToString();
                }

                return _result;
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show("错误", ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show("错误", ex.Message, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        public string[] GetProductCommand()
        {
            try
            {
                string[] _result = new string[((TestingConfig)testingConfig).TestParams.Length];

                for (int i = 0; i <= _result.Length - 1; i++)
                {
                    _result[i] = ((TestingConfig)testingConfig).TestParams[i].ProductCommand.ToString();
                }

                return _result;
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        public string[] GetTestIndex()
        {
            try
            {
                string[] _result = new string[((TestingConfig)testingConfig).TestParams.Length];

                for (int i = 0; i <= _result.Length - 1; i++)
                {
                    _result[i] = ((TestingConfig)testingConfig).TestParams[i].TestIndex.ToString();
                }

                return _result;
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        public string[] GetFixtureCommand()
        {
            try
            {
                string[] _result = new string[((TestingConfig)testingConfig).TestParams.Length];

                for (int i = 0; i <= _result.Length - 1; i++)
                {
                    _result[i] = ((TestingConfig)testingConfig).TestParams[i].FixtureCommand.ToString();
                }

                return _result;
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        public string[] GetTestLimit()
        {
            try
            {
                string[] _result = new string[((TestingConfig)testingConfig).TestParams.Length];
                string[] _resultLeft = new string[((TestingConfig)testingConfig).TestParams.Length];
                string[] _resultRight = new string[((TestingConfig)testingConfig).TestParams.Length];
                string[] _temp = null;

                for (int i = 0; i <= _result.Length - 1; i++)
                {
                    _result[i] = ((TestingConfig)testingConfig).TestParams[i].TestLimit.ToString();
                    _temp = _result[i].Split(',');
                    _resultLeft[i] = _temp[0];
                    _resultRight[i] = _temp[1];
                }

                SetTestLimitLeft(_resultLeft);
                SetTestLimitRight(_resultRight);

                return _result;
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        private string[] _testLimitLeft = null;
        private string[] _testLimitRight = null;
        public string[] GetTestLimitLeft()
        {
            try
            {
                return _testLimitLeft;
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        public void SetTestLimitLeft(string[] arg)
        {
            try
            {
                this._testLimitLeft = arg;
            }
            catch(System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (System.ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void SetTestLimitRight(string[] arg)
        {
            try
            {
                this._testLimitRight = arg;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (System.ArgumentNullException ex)
            {
                MessageBox.Show(ex.Message);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public string[] GetTestLimitRight()
        {
            try
            {
                return _testLimitRight;
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
            catch (System.ArgumentOutOfRangeException ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }
        }
        public string GetTestType()
        {
            return ((TestingConfig)testingConfig).TestType.ToString();
        }
        public void SetSwitchRF(int SwitchRF)
        {
            iSA.SetRefLvlOffset(powerEfficient.GetMulitPortTestFixtureCalibarteValue()[SwitchRF]);
            
            switch (SwitchRF)
            {
                case 0:
                    SetSwitchRF_ANT1ToRX1();
                    break;
                case 1:
                    SetSwitchRF_ANT3ToRX3();
                    break;
                case 2:
                    SetSwitchRF_ANT3ToRX3();
                    break;
                case 3:
                    SetSwitchRF_ANT4ToRX4();
                    break;
            }
        }
        private void SetSwitchRF_ANT1ToRX1()
        {
            try
            {
                ReturnCode rc;

                igfp.SetSwitch(1, 1, out rc);

                igfp.SetSwitch(2, 0, out rc);

                igfp.SetSwitch(3, 0, out rc);

                igfp.SetSwitch(4, 0, out rc);

                igfp.SetSwitch(9, 1, out rc);

                igfp.SetSwitch(10, 0, out rc);

                igfp.SetSwitch(11, 0, out rc);

                igfp.SetSwitch(12, 0, out rc);
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void SetSwitchRF_ANT2ToRX2()
        {
            try
            {
                ReturnCode rc;

                igfp.SetSwitch(1, 0, out rc);

                igfp.SetSwitch(2, 1, out rc);

                igfp.SetSwitch(3, 0, out rc);

                igfp.SetSwitch(4, 0, out rc);

                igfp.SetSwitch(9, 0, out rc);

                igfp.SetSwitch(10, 1, out rc);

                igfp.SetSwitch(11, 0, out rc);

                igfp.SetSwitch(12, 0, out rc);
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void SetSwitchRF_ANT3ToRX3()
        {
            try
            {
                ReturnCode rc;

                igfp.SetSwitch(1, 0, out rc);

                igfp.SetSwitch(2, 0, out rc);

                igfp.SetSwitch(3, 1, out rc);

                igfp.SetSwitch(4, 0, out rc);

                igfp.SetSwitch(9, 0, out rc);

                igfp.SetSwitch(10, 0, out rc);

                igfp.SetSwitch(11, 1, out rc);

                igfp.SetSwitch(12, 0, out rc);
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void SetSwitchRF_ANT4ToRX4()
        {
            try
            {
                ReturnCode rc;

                igfp.SetSwitch(1, 0, out rc);

                igfp.SetSwitch(2, 0, out rc);

                igfp.SetSwitch(3, 0, out rc);

                igfp.SetSwitch(4, 1, out rc);

                igfp.SetSwitch(9, 0, out rc);

                igfp.SetSwitch(10, 0, out rc);

                igfp.SetSwitch(11, 0, out rc);

                igfp.SetSwitch(12, 1, out rc);
            }
            catch (System.NullReferenceException ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        public void SetSwitchRF(byte portName, byte portState)
        {
            Fingu.AISG.ReturnCode rc;

            igfp.SetSwitch(portName, portState, out rc);
        }
        public struct SwichRF
        {
            public byte ANT1;
            public byte ANT2;
            public byte ANT3;
            public byte ANT4;
            public byte RX1;
            public byte RX2;
            public byte RX3;
            public byte RX4;
            public byte ON;
            public byte OFF;
        }
        public void InitSwichRF(SwichRF swichRF)
        {
            swichRF.ANT1 = 1;
            swichRF.ANT2 = 2;
            swichRF.ANT3 = 3;
            swichRF.ANT4 = 4;
            swichRF.RX1 = 9;
            swichRF.RX2 = 10;
            swichRF.RX3 = 11;
            swichRF.RX4 = 12;
            swichRF.ON = 1;
            swichRF.OFF = 0;
        }
        public int GetCalibarteCount()
        {
            return 4;
        }
    }

}